import { IBreadCrumb } from '@/components/nav-header/src/c-cpns/types/types'
import { RouteRecordRaw } from 'vue-router'
// 加载所有路由
export function mapAllRouter() {
  const allRoutes: RouteRecordRaw[] = []
  const routerFiles = require.context('@/router/main', true, /\.ts/)
  routerFiles.keys().forEach((key) => {
    const route = require('@/router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })
  return allRoutes
}
export function mapMenuToRoutes(userMenus: RouteRecordRaw[]) {
  const routes: RouteRecordRaw[] = []
  const allRoutes: RouteRecordRaw[] = mapAllRouter()
  const _recurseGetRoutes = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => route.path === menu.url)
        if (route) {
          routes.push(route)
        }
      } else {
        _recurseGetRoutes(menu.children)
      }
    }
  }
  _recurseGetRoutes(userMenus)
  return routes
}

export function pathMapBreadcrumbs(userMenus: any[], currentPath: string) {
  const breadcrumbs: IBreadCrumb[] = []
  pathMapToMenu(userMenus, currentPath, breadcrumbs)
  return breadcrumbs
}
export const pathMapToMenu = (
  userMenus: any[],
  currentPath: string,
  breadcrumbs?: IBreadCrumb[]
): any => {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
      if (findMenu) {
        breadcrumbs?.push({ name: menu.name })
        breadcrumbs?.push({ name: findMenu.name })
        return findMenu
      }
      return findMenu
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
}
